package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 自定义定时任务，实现订单状态定时处理
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 处理支付超时订单
     * 下单后超过15分钟仍未支付则判定为支付超时订单
     * 通过定时任务每分钟检查一次是否存在支付超时订单，如果存在则修改订单状态为“已取消”
     */
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeoutOrder() {
        log.info("处理支付超时订单（每分钟执行一次）");
        Integer status = Orders.PENDING_PAYMENT;
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);

        List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(status, time);

        if (ordersList != null && ordersList.size() != 0) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.CANCELLED);
                orders.setCancelTime(LocalDateTime.now());
                orders.setCancelReason(MessageConstant.PAY_OVER_TIME);
                orderMapper.update(orders);
            }
        }
    }

    /**
     * 处理“派送中”状态的订单
     * 通过定时任务每3小时检查一次是否存在“派送中”的订单，如果存在则修改订单状态为“已完成”
     */
    @Scheduled(cron = "0 0 0/3 * * ?")
    public void processDeliveryOrder() {
        log.info("处理派送中订单（每3小时执行一次）");
        Integer status = Orders.DELIVERY_IN_PROGRESS;
        LocalDateTime time = LocalDateTime.now().plusHours(-3);

        List<Orders> ordersList = orderMapper.getByStatusAndOrdertimeLT(status, time);

        if (ordersList != null && ordersList.size() != 0) {
            for (Orders orders : ordersList) {
                orders.setStatus(Orders.COMPLETED);
                orderMapper.update(orders);
            }
        }
    }

}